package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.hibernate.Session;
import org.hibernate.Transaction;

import beans.HibernateSessionFactory;


/**
 * 事务代理
 * @author wjm
 *
 */
public class TransactionHandler implements InvocationHandler {
	private Object obj;// 业务对象

	public TransactionHandler(Object obj) {
		super();
		this.obj = obj;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = session.beginTransaction();
		try{
			//调用业务方法 
			Object o = method.invoke(obj, args);
			tx.commit();
			return o;
		}catch(Exception e){
			tx.rollback();
			throw e;
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
}
